package com.css.bjdt_core.dailyReport.service;

import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.css.bjdt_core.annual.entity.RptAnnual;
import com.css.bjdt_core.annual.service.AnnualService;
import com.css.bjdt_core.reportPrepare.entity.RptBatch;
import com.css.bjdt_core.reportPrepare.entity.RptBatchDzzRel;
import com.css.bjdt_core.reportPrepare.entity.RptUnitAnnualRel;
import com.css.bjdt_core.reportPrepare.service.RptDealWithService;
import com.css.bjdt_core.util.CommonUtil;

@Service
public class DailyReportService {

	@Autowired
	private RptDealWithService rptDealWithService;

	@Autowired
	private AnnualService annualService;

	@Autowired
	private Dao dao;

	@Transactional
	public RptBatch toDailyUpdateTime(String dzzId, String dailyAnnualId, String unitId) {
		//先根据党组织ID和年度ID获得当前这个版本的批次，如果存在直接返回出去，如果不存在就需要创建新的批次
		RptBatchDzzRel rptBatchDzzRel = rptDealWithService.getARptBatchDzzRel(dzzId, dailyAnnualId);
		if (rptBatchDzzRel == null) {
			RptAnnual rptAnnual = annualService.queryByID(dailyAnnualId);
			String batchId = CommonUtil.getUUID();
			RptBatch rptBatch = new RptBatch();
			rptBatch.setId(batchId);
			rptBatch.setStartTime(rptAnnual.getStartTime());
			rptBatch.setEndTime(rptAnnual.getEndTime());

			RptBatchDzzRel rptBatchDzzRelNew = new RptBatchDzzRel();
			rptBatchDzzRelNew.setAnnualId(dailyAnnualId);
			rptBatchDzzRelNew.setDzzId(dzzId);
			rptBatchDzzRelNew.setId(batchId);

			//再把批次和当前这个单位的UNITID挂上钩
			RptUnitAnnualRel rptUnitAnnualRel = new RptUnitAnnualRel();
			rptUnitAnnualRel.setAnnualId(dailyAnnualId);
			rptUnitAnnualRel.setDzzId(dzzId);
			rptUnitAnnualRel.setUnitId(unitId);
			dao.insert(rptBatch);
			dao.insert(rptBatchDzzRelNew);
			dao.insert(rptUnitAnnualRel);
			return rptBatch;
		} else {
			return rptDealWithService.queryBatch(rptBatchDzzRel.getId());
		}
	}
}
